package main

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"strconv"
	"time"

	//"strconv"

)

type Many struct{
	beego.Controller
}

type ProductType struct{
	Id int `orm:"pk;auto"`
	Name string
}

type Product struct{
	Id int `orm:"pk;auto"`
	Name string
	Type *ProductType `orm:"rel(fk)"`
}

type ProjectType struct{
	Id int `orm:"pk;auto"`
	Name string
}

type Project struct{
	Id int `orm:"pk;auto"`
	Name string
	Type *ProjectType `orm:"rel(fk)"`
}

type Meal struct{
	Id int `orm:"pk;auto"`
	Name string
	ProjectList []*Project `orm:"rel(m2m)"`
	ProductList []*Product `orm:"rel(m2m)"`
}

type Member struct{
	Id int `orm:"pk;auto"`
	Name string `orm:"index"`
	Age int
	Sex int
	Level int
	Meallist []*Meal `orm:"rel(m2m)"`
	CreatedAt time.Time `orm:"auto_now_add;type(datetime)"`
	UpdatedAt time.Time `orm:"auto_now;type(datetime)"`
}

func init(){
	orm.Debug = true
	orm.RegisterDataBase("default", "mysql", "root:new_password@tcp(127.0.0.1:3306)/orm_insert?charset=utf8")
	orm.RegisterModel(new(ProductType), new(Product), new(ProjectType), new(Project), new(Meal), new(Member))
	orm.RunSyncdb("default", false, true)
}

// func (m *Many)Favicon(){
// 	return
// }

// func (m *Many) Index(){
// 	m.TplName = "temOne/beegoForm.html"
// }

func (m *Many)QueryMember(){
	o := orm.NewOrm()

	//gorm分页查询
	//db.Limit(5).Offset(5)

	//xorm分页查询
	//Limit(limit,index*limit)


	var ms []*Member

	username := m.GetString("username")
	address := m.GetString("address")

	if errj := json.Unmarshal([]byte(address), &ms); errj == nil{
		for _, jv := range ms{
			b := Member{Id: jv.Id}
			bErr := o.Read(&b)
			if bErr == orm.ErrNoRows {
				fmt.Println(jv)
				o.Insert(jv)
			}

			for _, mv := range jv.Meallist{
				e := Meal{Id: mv.Id}
				rErr := o.Read(&e)
				if rErr == orm.ErrNoRows {
					fmt.Println(mv)
					o.Insert(mv)
				}

				mm2m := o.QueryM2M(jv, "Meallist")
				_, err := mm2m.Add(mv)
				if err != nil{
					m.Data["json"] = map[string]interface{}{"error": errj}
					m.ServeJSON()
				}

				for _, mvj := range mv.ProjectList{
					jt := ProjectType{Id: mvj.Type.Id}
					jtErr := o.Read(&jt)
					if jtErr == orm.ErrNoRows {
						fmt.Println(mvj.Type)
						o.Insert(mvj.Type)
					}

					j := Project{Id: mvj.Id}
					jErr := o.Read(&j)
					if jErr == orm.ErrNoRows {
						fmt.Println(mvj)
						o.Insert(mvj)
					}

					jm2m := o.QueryM2M(mv, "ProjectList")
					_, err := jm2m.Add(mvj)
					if err != nil{
						m.Data["json"] = map[string]interface{}{"error": errj}
						m.ServeJSON()
					}

				}
				for _, mvd := range mv.ProductList{
					dt := ProductType{Id: mvd.Type.Id}
					dtErr := o.Read(&dt)
					if dtErr == orm.ErrNoRows {
						fmt.Println(mvd.Type)
						o.Insert(mvd.Type)
					}

					d := Project{Id: mvd.Id}
					dErr := o.Read(&d)
					if dErr == orm.ErrNoRows {
						fmt.Println(mvd)
						o.Insert(mvd)
					}

					pm2m := o.QueryM2M(mv, "ProductList")
					_, err := pm2m.Add(mvd)
					if err != nil{
						m.Data["json"] = map[string]interface{}{"error": errj}
						m.ServeJSON()
					}

				}
			}
		}

		m.Data["json"] = map[string]interface{}{"code": 200, "msg": "插入成功", "usernsme":username}
		m.ServeJSON()
	} else {
		m.Data["json"] = map[string]interface{}{"error": errj}
		m.ServeJSON()
	}

	// json.Unmarshal(m.Ctx.Input.RequestBody, &ms)
	// fmt.Println(ms)
	// for _, jv := range ms{
	// 	fmt.Println(jv)
	// 	for _, mv := range jv.Meallist{
	// 		fmt.Println(mv)
	// 		for _, mvj := range mv.ProjectList{
	// 			fmt.Println(mvj)
	// 		}
	// 		for _, mvd := range mv.ProductList{
	// 			fmt.Println(mvd)
	// 		}
	// 	}
	// }

	// m.Data["json"] = map[string]interface{}{"code": 200, "msg": "ok"}
	// m.ServeJSON()
}

func (m *Many)CombinedQuery() {

	o := orm.NewOrm()

	var memberList []*Member
	filter := o.QueryTable("member")

	id := m.GetString("id")
	name := m.GetString("name")
	age := m.GetString("age")
	sex := m.GetString("sex")
	level := m.GetString("level")
	createdAt := m.GetString("createdAt")
	pageSize, _ := strconv.Atoi(m.GetString("pageSize"))
	pageNo, _ := strconv.Atoi(m.GetString("pageNo"))

	if id != ""{
		filter = filter.Filter("id", id)
	}

	if name != ""{
		filter = filter.Filter("name", name)
	}

	if age != ""{
		filter = filter.Filter("age__gt", age)
	}

	if sex != ""{
		filter = filter.Filter("sex", sex)
	}

	if level != ""{
		filter = filter.Filter("level__lte",level)
	}

	if createdAt != ""{
		filter = filter.Filter("created_at__gte",createdAt)
	}

	filter.OrderBy("-created_at").Limit(pageSize, (pageNo-1)*pageSize).All(&memberList)

	m.Data["json"] = map[string]interface{}{"code": 200, "msg": "成功", "data":memberList}
	m.ServeJSON()
}

func main(){
	beego.BConfig.WebConfig.Session.SessionOn = true
	beego.Router("/passingJsonBeego", &Many{},"POST:QueryMember")
	//beego.Router("/deleteMeal", &Many{},"GET:DeleteMeal")
	//beego.Router("/updateMeal", &Many{},"GET:UpdateMeal")
	// beego.Router("/", &Many{},"GET:Index")
	// beego.Router("/favicon.ico", &Many{},"*:Favicon")
	beego.Router("/combinedQuery", &Many{},"POST:CombinedQuery")
	beego.Run()
}
